package com.xywy.bloodandroid.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.adapter.ExperReplayAdapter;
import com.xywy.bloodandroid.bean.DoctorReply;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.JsonUtil;
import com.xywy.bloodandroid.util.LogUtil;
import com.xywy.bloodandroid.util.NetUtil;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.GetRequest;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.VolleyManager;

public class PatientCommentFragement extends Fragment implements
		OnClickListener, OnScrollListener {

	protected static final int DOCTORREPLYERROR = 1;

	protected static final int DOCTORREPLYSUCESS = 2;

//	private FrameLayout share_exprence_button;

	private List<DoctorReply> list;
	private ListView listview;
	protected ProgressDialog waittingDialog;
	private ExperReplayAdapter adapter2;

	private int pageNum = 1;
	private int pageCount = 20;
	private String expertid;

	private boolean isLoadMore = true;
	private int visibleLastIndex = 0;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragement_patient_comment, null);
		initView(view);
		initListener();
		initdata();
		return view;

	}

	private void initdata() {
		Bundle b = this.getArguments();
		expertid = getArguments().getString("expertid");
		
		int flag = getArguments().getInt("flag", -1);
	    id = getArguments().getString("document_id");
//		if (flag == -100) {
//			display_rel.setVisibility(View.GONE);
//		}
		getDoctorReplay( id);

	}

	private void getDoctorReplay(String id) {
		isLoadMore = true;
		final Message msg = Message.obtain();
		GetRequest<String> getRequest = new GetRequest<String>(Constants.getUrl(
				"zhuanjia", "DoctorRely")
				+ "&expertid="
				+ expertid
				+ "&pageNum=" + pageNum + "&pageCount=20", String.class,
				new OnVolleyResponseListener<String>() {
					@Override
					public void onError(VolleyError volleyError) {

						msg.what = DOCTORREPLYERROR;
						handler.sendMessage(msg);

					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(getActivity(), waittingDialog);
						LogUtil.i("获取的返回值", response);
						JSONObject jsonObject;
						try {
							jsonObject = new JSONObject(response);
							String code = jsonObject.optString("code");
							String data = jsonObject.optString("data");
							if (code.equals("10000")) {
								ParseDoctorReplyJson(response);
								msg.what = DOCTORREPLYSUCESS;
								handler.sendMessage(msg);
							} else {
								String error = jsonObject.optString("error");
								UIUtil.showToast(getActivity(), error);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
		getRequest.setIsParseJson(false);
		if (NetUtil.hasNetwork(getActivity())) {
			if (pageNum == 1)
				waitingDialog(getActivity(), getActivity().getResources()
						.getString(R.string.request));
			VolleyManager.addRequest(getRequest, getActivity());
		} else {
			UIUtil.showToast(getActivity(), getActivity().getResources()
					.getString(R.string.not_network));
			UIUtil.DissDialog(getActivity(), waittingDialog);
		}

	}

	private void ParseDoctorReplyJson(String value) {
		try {
			JSONObject object = new JSONObject(value);
			String data = object.optString("data");
			//
			list.addAll((List<DoctorReply>) JsonUtil.parseJsonToList(data,
					new TypeToken<List<DoctorReply>>() {
					}.getType()));
			System.out.println("获取专家回复的大小.." + list.size());
		} catch (Exception e) {
			LogUtil.i("专家回复", "Json解析异常");
			e.printStackTrace();
		}
	}

	public void waitingDialog(Context context, String message) {
		if (waittingDialog == null)
			waittingDialog = new ProgressDialog(context);
		waittingDialog.setCanceledOnTouchOutside(false);//
		waittingDialog.setMessage(message);
		waittingDialog.show();
	}

	private void initListener() {
//		share_exprence_button.setOnClickListener(this);
		listview.setOnScrollListener(this);
	}

	private void initView(View view) {
//		share_exprence_button = (FrameLayout) view
//				.findViewById(R.id.share_exprence_button);
		listview = (ListView) view.findViewById(R.id.listview);
		list = new ArrayList<DoctorReply>();

		list_footer = (LinearLayout) getActivity().getLayoutInflater().inflate(
				R.layout.list_footer, null);

		list_footer.setVisibility(View.GONE);
		tv_msg = (TextView) list_footer.findViewById(R.id.tv_msg);
		loading = (LinearLayout) list_footer.findViewById(R.id.loading);
		listview.addFooterView(list_footer);

		adapter2 = new ExperReplayAdapter(getActivity(), list);
		listview.setAdapter(adapter2);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
//		case R.id.share_exprence_button: // ���������Ϊ ������ר��ҳ��
//			// Intent intent=new Intent(getActivity(),
//			// ShareMyExperenceAct.class);
//			Intent intent = new Intent(getActivity(), FreeAskQuestionAct.class);
//			intent.putExtra("mark", -100);
//			startActivity(intent);
//			break;
		default:
			break;
		}

	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case DOCTORREPLYERROR:
				UIUtil.DissDialog(getActivity(), waittingDialog);
				UIUtil.showToast(getActivity(),
						getResources().getString(R.string.network_slow));
				break;
			case DOCTORREPLYSUCESS:

				if (list.size() > 0 & list.size() <= pageCount * pageNum
						& pageCount > 0) {
					list_footer.setVisibility(View.VISIBLE);
					tv_msg.setVisibility(View.VISIBLE);
					loading.setVisibility(View.GONE);
				}
				if (list.size() < 20 || list.size() < pageCount * pageNum) {
					// list_footer.setVisibility(View.GONE);
					listview.removeFooterView(list_footer);

				}
				adapter2.notifyDataSetChanged();

				break;

			default:
				break;
			}
		}
	};

	private TextView tv_msg;

	private LinearLayout loading;

	private LinearLayout list_footer;

	private String id;

	@Override
	public void onScroll(AbsListView arg0, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		visibleLastIndex = firstVisibleItem + visibleItemCount;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		int itemsLastIndex = adapter2.getCount(); //
		int lastIndex = itemsLastIndex + 1; //
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& visibleLastIndex == lastIndex) {
			if (isLoadMore) {
				isLoadMore = false;
				pageNum++;
				Log.i("pageNo", "..." + pageNum + "......");
				tv_msg.setVisibility(View.GONE);
				loading.setVisibility(View.VISIBLE);
				getDoctorReplay(id);
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		VolleyManager.cancelRequest(getActivity());
	}
}
